using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Text;

namespace PicoInterface
{
    /// <summary>
    /// Summary description for PicoInvoke.
    /// </summary>
    sealed class PicoInvoke
    {
        [DllImport("PicoInvoke.dll", EntryPoint = "#1")]
        public static extern Boolean CreatePicoXface(String program_name);

        [DllImport("PicoInvoke.dll", EntryPoint = "#2")]
        public static extern Boolean GetCurrentImage(StringBuilder image_name_out);

        [DllImport("PicoInvoke.dll", EntryPoint = "#3")]
        public static extern Int32 GetLastErrorCode();
        
        [DllImport("PicoInvoke.dll", EntryPoint = "#4")]
        public static extern Int32 GetLastErrorMessage(StringBuilder program_name);

        [DllImport("PicoInvoke.dll", EntryPoint = "#5")]
        public static extern Int32 ReadDevice(Int32 address);

        [DllImport("PicoInvoke.dll", EntryPoint = "#6")]
        public static extern Int32 ReadDeviceArray(Int32 address, ushort[] data, Int32 length);

        [DllImport("PicoInvoke.dll", EntryPoint = "#7")]
        public static extern Boolean Reboot(string image_name, Boolean run_linked);


        [DllImport("PicoInvoke.dll", EntryPoint = "#8")]
        public static extern Int32 WriteDevice(Int32 address, Int32 data);

        [DllImport("PicoInvoke.dll", EntryPoint = "#9")]
        public static extern Int32 WriteDeviceArray(Int32 address, ushort[] data, Int32 length);


        public static string GetLastError()
        {
            StringBuilder oErrorMessage = new StringBuilder(1024, 1024);
            int iLastError = GetLastErrorMessage(oErrorMessage);
            if (oErrorMessage.ToString().Substring(oErrorMessage.ToString().Length - 13, 13) != "Unknown error")
            {
                return "Error Code: " + iLastError.ToString() + "\n" + oErrorMessage.ToString();
            }
            else
                return "Unknown Error";
        }
    }
}
